//
//  ApiTaskBase.m
//  ApiBase
//
//  Created by Liam on 12-10-3.
//  Copyright 2012 __MyCompanyName__. All rights reserved.
//

#import "ApiTaskBase.h"
#import "HttpConn.h"
#import "APIUtil.h"
#import "GDataDefines.h"
#import "CmnFunc.h"

@interface ApiTaskBase()

- (NSString *)getUrl;
- (NSData *)getHTTPBody;
- (NSInputStream *)getHTTPStreamBody;
- (NSString *)getMethod;
- (NSDictionary *)getHeaders;
- (id)connectionDelegate;

@end

@implementation ApiTaskBase

@synthesize taskType = _taskType;
@synthesize params = _params;
@synthesize delegate = _delegate;
@synthesize context = _context;

- (id)init
{
	self = [super init];
	
	[self setQueuePriority:[self _queuePriority]];
	[self setThreadPriority:[self _threadPriority]];
	
	return self;
}

- (void)dealloc
{
	self.params = nil;
	self.delegate = nil;
	self.context = nil;
	SAFE_RELEASE(_httpConn);
	
	[super dealloc];
}

- (void)main
{
	NSError *error = [self _checkEnvBeforeProcess];
	
	if (!error)
	{
		@synchronized(self)
		{
			_httpConn = [[HttpConn alloc] init];
		}
		
		if (_httpConn)
		{
			NSString *urlString = [self getUrl];
			NSDictionary *headers = [self getHeaders];
			NSString *method = [self getMethod];
			NSData *body = [self getHTTPBody];
			NSInputStream *streamBody = [self getHTTPStreamBody];
			
			NSMutableURLRequest *connectionRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString: urlString]];
			[connectionRequest setHTTPMethod:method];
			[connectionRequest setTimeoutInterval:30.0];
			[connectionRequest setCachePolicy:NSURLRequestUseProtocolCachePolicy];
			if (streamBody)
			{
				[connectionRequest setHTTPBodyStream:streamBody];
			}
			else if (body)
			{
				[connectionRequest setHTTPBody:body];
			}
			
			if (headers)
			{
				for (NSString * key in [headers allKeys])
				{
					NSString *value = [NSString stringWithFormat:@"%@", [headers valueForKey:key]];
					//NSLog(@"header key:%@ value:%@", key, value);
					[connectionRequest setValue:value forHTTPHeaderField:key];
				}
			}
			
			NSLog(@"Request Headers : %@", [[connectionRequest allHTTPHeaderFields] description]);
			
			NSOutputStream *outStream = [NSOutputStream outputStreamToMemory];
			[outStream open];
			
			error = [_httpConn executeRequest:connectionRequest withOutStream:outStream connectionDelegate:[self connectionDelegate]];
			NSData * data = [outStream propertyForKey:NSStreamDataWrittenToMemoryStreamKey];
			
			[outStream close];
			
			[self _dealWithResponse:data withError:error];
		}
	}
	else
	{
		[self _dealWithResponse:nil withError:error];
	}
	
	self.params = nil;
	self.delegate = nil;
	
	NSLog(@"task type:%d finished with error %@", self.taskType, error);
}

- (void)cancel
{
	[super cancel];
	@synchronized(self)
	{
		if (_httpConn)
		{
			[_httpConn cancel];
		}
	}
}

- (NSError *)_checkEnvBeforeProcess
{
	return nil;
}

- (NSString *)getUrl
{
	NSString *strUrl = [self _getUrl];
	NSString *sParams = nil;
	
	NSString *method = [self getMethod];
	if ([method compare:@"POST"] != NSOrderedSame)
	{
		sParams = SAFE_FORMAT_STRING([self _getRequestParams]);
	}
	
	if (sParams && [sParams length] > 0)
	{
		strUrl = [strUrl stringByAppendingFormat:@"?%@", sParams];
	}
	
	NSLog(@"%@", strUrl);
	
	return strUrl;
}

- (NSData *)getHTTPBody
{
	return [self _getHTTPBody];
}

- (NSInputStream *)getHTTPStreamBody
{
	return [self _getHTTPStreamBody];
}

- (NSString *)getMethod
{
	return [self _getMethod];
}

- (NSDictionary *)getHeaders
{
	NSMutableDictionary * headers = [NSMutableDictionary dictionary];
	
	NSDictionary* selfHeaders = [self _getHeaders];
	if (selfHeaders)
	{
		[headers setValuesForKeysWithDictionary:selfHeaders];
	}
	
	//NSLog(@"headers %@", [headers description]);
	
	return headers;
}

- (id)connectionDelegate
{
	return [self _connectionDelegate];
}

- (void)_dealWithResponse:(NSData *)data withError:(NSError *)error
{
}

- (NSString*)_getServerUrl
{
	return [APIUtil getAPIServerUrl];
}

- (NSString*)_getUrl
{
	NSString* strUrl = [NSString stringWithFormat:@"%@%@",
						[self _getServerUrl],
						SAFE_FORMAT_STRING([self _getRequestURI]),
						nil];
	return strUrl;
}

- (NSString *)_getRequestURI
{
	return nil;
}

- (NSString*)_getRequestParams
{
	NSMutableString* str = nil;
	
	if (_params)
	{
		str = [NSMutableString stringWithCapacity:1024];
		int i = 0;
		
		for (NSString* key in [_params allKeys])
		{
			if ([self _ignoreParamKey:key])
				continue;
			NSString *value = [NSString stringWithFormat:@"%@", [_params valueForKey:key]];
			[str appendFormat:(i++ == 0 ? @"?%@=%@" : @"&%@=%@"), key, [CmnFunc URLEncode:value]];
		}
	}
	
	return str;
}

- (BOOL)_ignoreParamKey:(NSString *)key
{
	return NO;
}

- (NSData *)_getHTTPBody
{
	NSData *data = nil;
	
	NSString *method = [self getMethod];
	if ([method compare:@"POST"] == NSOrderedSame)
	{
		NSString *sParams = SAFE_FORMAT_STRING([self _getRequestParams]);
		if (sParams && [sParams length] > 0)
		{
			NSLog(@"Http Body : %@", sParams);
			data = [sParams dataUsingEncoding:NSUTF8StringEncoding];
		}
	}
	
	return data;
}

- (NSInputStream*)_getHTTPStreamBody
{
	return nil;
}

- (NSString *)_getMethod
{
	return @"GET";
}

- (NSDictionary *)_getHeaders
{
	return nil;
}

- (BOOL)_needSignature
{
	return YES;
}

- (BOOL)_needSessionKey
{
	return YES;
}

- (id)_connectionDelegate
{
	return nil;
}

- (NSOperationQueuePriority)_queuePriority
{
	return NSOperationQueuePriorityNormal;
}

- (double)_threadPriority
{
	return 0.5;
}

- (BOOL)_needSecurity
{
	return NO;
}

@end
